package com.translate.web.config;

import java.util.Date;

import javax.crypto.SecretKey;

import org.springframework.stereotype.Component;

import com.jwt.JwtConfig;
import com.jwt.JwtTokenUtil;
import com.translate.web.config.contract.IJwtExtend;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

@Component(value = "JwtExtend")
public class JwtExtend extends JwtTokenUtil implements IJwtExtend {

	@Override
	public String getRealname(String token) {

		return getDataByKey(token, "realname");

	}
	
	@Override
	public String getMobile(String token) {
		// TODO Auto-generated method stub
		return getDataByKey(token, "mobile");
	}

	
	public String getDataByKey(String token, String key) {

		JwtConfig jwtConfig = this.getJwtConfig();

		token = token.replace(jwtConfig.getHeaderFlag(), "");
		// 验证是否已过期
		if (isTokenExpired(token)) {
			return "";
		}

		String username;
		try {
			Claims claims = getClaimsFromToken(token);
			username = claims.get(key).toString();
		} catch (Exception e) {
			e.printStackTrace();
			username = null;
		}
		return username;

	}

	/**
	 * 判断token是否已经失效
	 */
	private boolean isTokenExpired(String token) {
		Date expiredDate = getExpiredDateFromToken(token);
		return expiredDate.before(new Date());
	}

	/**
	 * 从token中获取过期时间
	 */
	private Date getExpiredDateFromToken(String token) {
		Claims claims = getClaimsFromToken(token);
		return claims.getExpiration();
	}

	/**
	 * 从token中获取JWT中的负载
	 */
	private Claims getClaimsFromToken(String token) {
		Claims claims = null;
		try {
			JwtConfig jwtConfig = this.getJwtConfig();

			SecretKey secretKey = Keys.hmacShaKeyFor(jwtConfig.getSecret().getBytes());
			claims = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return claims;
	}

	
}
